//
//  OnlinePeopleView.m
//  YouinRTCDemo
//
//  Created by 潘欣 on 2023/6/23.
//

#import "OnlinePeopleView.h"
#import <LSTPopView.h>
#import "OnLinePeopleCell.h"
#import "AFNetworking.h"
#import "OnlineModel.h"
#import "PrivateChatView.h"
@interface OnlinePeopleView ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,weak) LSTPopView *popView;
@property (nonatomic,strong)UILabel *label;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)NSTimer *dataTimer;
@property(nonatomic,assign)int seconds;
@end

@implementation OnlinePeopleView

- (instancetype)initWithFrame:(CGRect)frame
{
    if ([super initWithFrame:frame]) {
        self.seconds = 10;
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/3*2.2-110)];
        view.backgroundColor = [UIColor whiteColor];
        [self addSubview:view];
        
        self.label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, SCREEN_WIDTH-30, 25)];
        self.label.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
        self.label.textColor = [UIColor blackColor];
        self.label.text = @"在线人数";
        [view addSubview:self.label];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn addTarget:self action:@selector(flushBtn) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitle:@"刷新" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:13];
        btn.frame = CGRectMake(SCREEN_WIDTH-70, 20, 55, 25);
        btn.backgroundColor = rgba(25, 148, 255, 1);
        btn.layer.cornerRadius = 3;
        [view addSubview:btn];
        
        
        UILabel *tips = [[UILabel alloc] initWithFrame:CGRectMake(btn.frame.origin.x-200, 20,200, 25)];
        tips.font = [UIFont systemFontOfSize:10];
        tips.textColor = [UIColor lightGrayColor];
        tips.textAlignment = NSTextAlignmentRight;
        
        tips.text = @"每10秒刷新一次数据或者点击【刷新】";
        [view addSubview:tips];
        
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.frame = CGRectMake(0, self.label.frame.origin.y+self.label.frame.size.height+10, SCREEN_WIDTH, view.frame.size.height-60);
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = YES;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        _tableView.estimatedRowHeight = 100;
        _tableView.rowHeight = 60;//UITableViewAutomaticDimension;
        [_tableView registerClass:[OnLinePeopleCell class] forCellReuseIdentifier:@"OnLinePeopleCell"];
        
        [view addSubview:_tableView];
        
        if (@available(iOS 11.0, *)) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }else {
            
        }
        
        
        
        if (self.dataTimer == nil)
        {
            self.dataTimer = [NSTimer timerWithTimeInterval:1.0
                                                          target:self
                                                        selector:@selector(onlineRefresh)
                                                        userInfo:nil
                                                         repeats:YES];
            [[NSRunLoop mainRunLoop] addTimer:self.dataTimer forMode:NSRunLoopCommonModes];
        }
    }
    
    return self;
}

- (void)onlineRefresh
{
    self.seconds--;
    if (self.seconds == 0) {
        
//        NSLog(@"刷新了e");
        [self dataRequest];
        self.seconds = 10;
    }
//    NSLog(@"self.seconds");
}

- (void)setModel:(PrivateModel *)model
{
    _model = model;
    [self dataRequest];
}

- (NSMutableArray *)dataArray
{
    if(!_dataArray){
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (void)dataRequest
{
    [MBProgressHUD showHUDAddedTo:self animated:YES];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    
    NSString *urlString = [NSString stringWithFormat:@"%@v1/course/watch_user_list/%@/?page=1&size=100",HTTPSURL,self.model.liveId];
    
    NSDictionary *dict =  [[YouinRTCManager shardManager] readNSUserDefaults];
    NSDictionary *dicheaders = @{@"authorization":[NSString stringWithFormat:@"JWT %@",dict[@"token"]]};
    [manager GET:urlString parameters:nil headers:dicheaders progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self animated:YES];
        
        NSArray<OnlineModel *>*array = [OnlineModel mj_objectArrayWithKeyValuesArray:responseObject[@"result"]];
        self.dataArray = [array copy];
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self animated:YES];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    OnLinePeopleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OnLinePeopleCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    OnlineModel *onModel = self.dataArray[indexPath.row];
    cell.model = onModel;
    [cell.privateChat addTarget:self action:@selector(privateChatAction:) forControlEvents:UIControlEventTouchUpInside];
    objc_setAssociatedObject(cell.privateChat, @"model", cell.model, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    cell.message.hidden = YES;
    for (NSString *userId in self.model.userIdArr) {
        if (onModel.owner_id == userId){
            cell.message.hidden = NO;
        }
    }

    
    
    if (self.model.private_chat) {
        cell.privateChat.hidden = NO;
    }else{
        cell.privateChat.hidden = YES;
    }
    
    return cell;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    label.text = @"--- 最多展示100名用户 ---";
    label.textAlignment = 1;
    label.font = [UIFont systemFontOfSize:13];
    label.textColor = [UIColor lightGrayColor];
    return label;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 30.0;
}

- (void)privateChatAction:(UIButton *)sender
{
    OnlineModel *model = objc_getAssociatedObject(sender, @"model");
    
    NSMutableArray *toRemoveArr = [NSMutableArray array];
    for (NSString *owner_id in self.model.userIdArr) {
        if (model.owner_id == owner_id){
            [toRemoveArr addObject:owner_id];
        }
    }
    [self.model.userIdArr removeObjectsInArray:toRemoveArr];

    
    if([self.delegate respondsToSelector:@selector(ClearRedPoint:)]){
        [self.delegate ClearRedPoint:self.model.userIdArr.count];
    }
    
    [self.tableView reloadData];
//    PrivateChatView *chatView = [[PrivateChatView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,SCREEN_HEIGHT/3.0*1.8)];
//    PrivateModel *priModel = [PrivateModel new];
//    priModel = self.model;
//    priModel.userId = model.owner_id;
//    priModel.userName = model.nickname;
//    chatView.model = priModel;
//    [chatView show];
    PrivateChatView *chatView = [PrivateChatView sharedView];
    chatView.frame = CGRectMake(0, 0, SCREEN_WIDTH,SCREEN_HEIGHT/3.0*1.8);
    PrivateModel *priModel = [PrivateModel new];
    priModel = self.model;
    priModel.userId = model.owner_id;
    priModel.userName = model.nickname;
    chatView.model = priModel;
    [chatView show];
    
}


#pragma mark - 刷新
- (void)flushBtn
{
    [self dataRequest];
}

-(void)show
{
    LSTPopView *popView = [LSTPopView initWithCustomView:self
                                                popStyle:LSTPopStyleSmoothFromBottom
                                            dismissStyle:LSTDismissStyleSmoothToBottom];
    
    popView.hemStyle = LSTHemStyleBottom;
    popView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    LSTPopViewWK(popView)
    popView.popDuration = 0.5;
    popView.dismissDuration = 0.5;
    popView.isClickFeedback = YES;
    popView.rectCorners = UIRectCornerTopLeft | UIRectCornerTopRight;
    popView.cornerRadius = 15;
    popView.sweepStyle = LSTSweepStyleY_Positive;
    popView.dragStyle = LSTDragStyleY_Positive;
    popView.sweepDismissStyle = LSTSweepDismissStyleSmooth;
    popView.bgClickBlock = ^{
        NSLog(@"点击了背景");
       
        if(self.dataTimer!=nil){
            [self.dataTimer invalidate];
            self.dataTimer = nil;
        }
        [wk_popView dismiss];
    };
    self.popView = popView;
    
    [popView pop];
}

-(void)dealloc
{
    if(self.dataTimer!=nil){
        [self.dataTimer invalidate];
        self.dataTimer = nil;
    }
    NSLog(@"dealloc");
}
@end
